package com.shuguoyiyou.wechatofficialaccount.service.impl;

import com.shuguoyiyou.wechatofficialaccount.config.MyMetaObjectHandler;
import com.shuguoyiyou.wechatofficialaccount.config.WeiXinConfig;
import com.shuguoyiyou.wechatofficialaccount.entity.form.UserOpenIdForm;
import com.shuguoyiyou.wechatofficialaccount.provider.ResourceProvider;
import com.shuguoyiyou.wechatofficialaccount.service.RedisService;
import com.shuguoyiyou.wechatofficialaccount.service.WeiXinService;
import com.shuguoyiyou.wechatofficialaccount.service.MpUserInfoService;
import com.shuguoyiyou.wechatofficialaccount.util.QrCodeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * Created by ZengJian on 2021/3/1 0001 下午 5:48
 */
@AllArgsConstructor
@Service("iMpUserInfoService")
@Slf4j
public class IMpUserInfoService implements MpUserInfoService {

    private final WxMpService wxMpService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ResourceProvider resourceProvider;

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private WeiXinConfig weiXinConfig;

//    @Override
//    @Transactional
//    public String getSnsapiUserinfo(Map<String, Object> accesstokenInfo, String username){
//
//    }

    @Override
    @Transactional
    public String getCode() {
        String png_base64 = null;
        // 获取当前的用户
        MyMetaObjectHandler myMetaObjectHandler = new MyMetaObjectHandler();
        String username = myMetaObjectHandler.getCurrentUsername();

        Long currentTime = new Date().getTime();
        System.out.println("currentTime:" + currentTime);

        String value = currentTime + RandomStringUtils.randomAlphanumeric(6);
        redisService.set(username, value);
        redisService.expire(username, 60);
//        String requestUrl = "http://www.coolbreeze.top:80/wechatOfficialAccount/getWeiXinUserInfoByUsernameValue/" + username + "/" + value;
        String requestUrl = "http://wai.free.idcfengye.com:80/wechatOfficialAccount/getWeiXinUserInfoByUsernameValue/" + username + "/" + value;

        System.out.println("requestUrl" + requestUrl);
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            QrCodeUtil.encode(requestUrl, null, os);
            byte[] bytes = os.toByteArray();//转换成字节
            BASE64Encoder encoder = new BASE64Encoder();
            String png_base = encoder.encodeBuffer(bytes).trim();//转换成base64串
            png_base64 = png_base.replaceAll("\n", "").replaceAll("\r", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return png_base64;
    }


    @Override
    @Transactional
    public String getWeiXinUserInfoByUsernameValue(String code, String username, String value, HttpServletRequest request, HttpServletResponse response, HttpSession session) {

//        //第一步：用户同意授权，获取code
        if (!StringUtils.isNotBlank(redisService.get(username))) {
            String htmlFail = "<!DOCTYPE html>" +
                    "<html lang='en'>" +
                    "<head>" +
                    "  <meta charset='UTF-8'>" +
                    "  <meta name='viewport' content='initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no'>" +
                    "</head>" +
                    "<body>" +
                    "<h3>二维码已失效,请重新获取二维码</h3>" +

                    "</body>" +
                    "</html>" +
                    "<script type=\"text/javascript\">\n" +
                    "    // 关闭网站\n" +
                    "    // alert(typeof(WeixinJSBridge)); 输出undifined\n" +
                    "    setTimeout(function(){\n" +
                    "        // 原生浏览器\n" +
                    "        window.close();\n" +
                    "        \n" +
                    "        // 微信浏览器\n" +
                    "        document.addEventListener('WeixinJSBridgeReady', function(){\n" +
                    "            WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
                    "        }, false);\n" +
                    "        WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
                    "    }, 3000);\n" +
                    "</script>";
            return htmlFail;
        }
        System.out.println("value:" + value);
        if (code == null) {

            String url = URLEncoder.encode(request.getRequestURL().toString());
            System.out.println("url:" + url);
            String authorizeUrl = weiXinService.buildAuthorizeURL(url);
            System.out.println("authorizeUrl:" + authorizeUrl);
            try {
                response.sendRedirect(authorizeUrl);
            } catch (IOException e) {
                System.out.println(e);
            }

            return null;
        }
        //第二步：通过code换取网页授权access_token
        String htmlInfo = "";
        System.out.println("code:" + code);
        Map<String, Object> accesstokenInfo = weiXinService.getACCESSTOKEN(code);
        System.out.println("accesstokenInfo:" + accesstokenInfo);
        String errcode = (String) accesstokenInfo.get("errcode");
        System.out.println("errcode:" + errcode);
        if (StringUtils.isEmpty(errcode)) {
            //第四步：拉取用户信息(需scope为 snsapi_userinfo)
            Map<String, Object> weiXinUserInfo = weiXinService.getWeiXinUserInfo(accesstokenInfo);
            System.out.println("weiXinUserInfo:" + weiXinUserInfo);
            String userInfohtml = "";
            try {
                userInfohtml = createUserInfoHtml(weiXinUserInfo, username);
                System.out.println("userInfohtml:" + userInfohtml);
            } catch (WxErrorException e) {
                System.out.println(e);
            }

            return userInfohtml;
        }
        return htmlInfo;
    }

    /**
     * 生成微信用户信息Html
     *
     * @param weiXinUserInfo
     * @return
     */
    private String createUserInfoHtml(Map<String, Object> weiXinUserInfo, String username) throws WxErrorException {
        String wxOpenId = (String) weiXinUserInfo.get("openid");
        String nickname = (String) weiXinUserInfo.get("nickname");
        String subscribe = (String) weiXinUserInfo.get("subscribe");
        Double sex = (Double) weiXinUserInfo.get("sex");
        String country = (String) weiXinUserInfo.get("country");
        String sexString = "";
        if (sex == 1.0d) {
            sexString = "男";
        } else {
            sexString = "女";
        }
		/*String province = (String)weiXinUserInfo.get("province");
		String city = (String)weiXinUserInfo.get("city");
		String country = (String)weiXinUserInfo.get("country");*/
        String headimgurl = (String) weiXinUserInfo.get("headimgurl");
        WxMpUser wxMpUser = this.wxMpService.getUserService().userInfo(wxOpenId);
        String htmlInfo = "<!DOCTYPE html>" +
                "<html lang='en'>" +
                "<head>" +
                "  <meta charset='UTF-8'>" +
                "  <meta name='viewport' content='initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no'>" +
                "</head>" +
                "<body>" +
                "<h3>绑定系统账号成功</h3>" +

                "</body>" +
                "</html>" +
                "<script type=\"text/javascript\">\n" +
                "    // 关闭网站\n" +
                "    // alert(typeof(WeixinJSBridge)); 输出undifined\n" +
                "    setTimeout(function(){\n" +
                "        // 原生浏览器\n" +
                "        window.close();\n" +
                "        \n" +
                "        // 微信浏览器\n" +
                "        document.addEventListener('WeixinJSBridgeReady', function(){\n" +
                "            WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
                "        }, false);\n" +
                "        WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
                "    }, 3000);\n" +
                "</script>";

        UserOpenIdForm userOpenIdForm = new UserOpenIdForm();
        userOpenIdForm.setUsername(username);
        userOpenIdForm.setOpenId(wxOpenId);
        System.out.println("username:" + username + ":wxOpenId:" + wxOpenId);
        resourceProvider.updateOpenId(userOpenIdForm);
        return htmlInfo;
    }

}
